package tree

import "fmt"

/*
基于数组实现栈
*/

type ArrayStack struct {
	data []interface{} // 数据存储
	top  int           // 栈顶指针
}

func NewArrayStack() *ArrayStack {
	return &ArrayStack{
		data: make([]interface{}, 0, 32),
		top:  -1,
	}
}

func (that *ArrayStack) IsEmpty() bool {
	if that.top < 0 {
		return true
	}
	return false
}

func (that *ArrayStack) Push(v interface{}) {
	if that.top < 0 {
		that.top = 0
	} else {
		that.top += 1
	}

	if that.top > len(that.data)-1 {
		that.data = append(that.data, v)
	} else {
		that.data[that.top] = v
	}
}

func (that *ArrayStack) Pop() interface{} {
	if that.IsEmpty() {
		return nil
	}
	v := that.data[that.top]
	that.top--
	return v
}

func (that *ArrayStack) Top() interface{} {
	if that.IsEmpty() {
		return nil
	}
	return that.data[that.top]
}

func (that *ArrayStack) Flush() {
	that.top = -1
	that.data = make([]interface{}, 0, 32)
}

func (that *ArrayStack) Print() {
	if that.IsEmpty() {
		fmt.Println("empty stack")
	} else {
		for i := that.top; i >= 0; i-- {
			fmt.Println(that.data[i])
		}
	}
}
